﻿using Lamex.Common;
using Lamex.Interface;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Lamex.Library.CommonClass
{
   public class MdiTools
    {

        /// <summary>
        /// 取应用程序的主窗体
        /// </summary>
        public static Form MdiMainForm
        {
            get
            {
                foreach (Form form in Application.OpenForms)
                    if (form.IsMdiContainer) return form;
                return null;
            }
        }

        public static Form FindForm(string formTypeFullName)
        {
            foreach (Form form in Application.OpenForms)
            {
                if (form.GetType().FullName.ToUpper() == formTypeFullName.ToUpper())
                    return form;
            }
            return null;
        }


        //打开IE浏览器或打开Outlook
        public static void OpenIE(string url)
        {
            //System.Diagnostics.Process.Start(url);
            string[] pathFiles = url.Split(';');
            System.Diagnostics.Process p = new Process();

            if (pathFiles.Count() == 1)
            {
                p.StartInfo.UseShellExecute = true;

                p.StartInfo.FileName = pathFiles[0];
                //p.StartInfo.WorkingDirectory = @"M:\MES\ShareFolder\李钟哇\3TEC_New_Version\bin";
                //p.StartInfo.Arguments = @"M:\MES\ShareFolder\李钟哇\3TEC_New_Version\bin";
                p.Start();
            }
            else if (pathFiles.Count() == 2)
            {
                p.StartInfo.UseShellExecute = true;

                p.StartInfo.FileName = pathFiles[0];
                p.StartInfo.WorkingDirectory = pathFiles[1];
                //p.StartInfo.Arguments = @"M:\MES\ShareFolder\李钟哇\3TEC_New_Version\bin";
                p.Start();
            }
            else if (pathFiles.Count() == 3)
            {
                p.StartInfo.UseShellExecute = true;

                p.StartInfo.FileName = pathFiles[0];
                p.StartInfo.WorkingDirectory = pathFiles[1];
                p.StartInfo.Arguments = pathFiles[2];
                p.Start();
            }
        }

        /// <summary>
        /// 打开子窗体.
        /// </summary>
        /// <param name="mdi">MDI主窗体</param>
        /// <param name="formType">子窗体的类型</param>
        /// <param name="ToolStripMenuItem">打开窗体的菜单项</param>
        public static Form OpenChildForm(IMdiForm mdi, Type formType, ToolStripMenuItem sender)
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;
                Form form = ActiveChildForm(mdi as Form, formType.ToString()); 
                if (form != null) { form.Show(); return form; } 
                form = (Form)formType.Assembly.CreateInstance(formType.FullName);
                if (form == null) throw new Exception("未知窗体类型!");
                if (form is IMdiChildForm)
                {
                    form.MdiParent = (Form)mdi; 
                    (form as IMdiChildForm).ToolbarRegister = mdi.MdiToolbar; 
                    (form as IMdiChildForm).RegisterObserver(mdi.MdiObservers); 
                }

    
                if (form is IPurviewControllable)
                {
                    if (sender != null && sender.Tag is MenuItemTag)
                    {
                        MenuItemTag tag = sender.Tag as MenuItemTag;
                        //int auth = new bllGroupAuthority().GetFormAuthority(Loginer.CurrentUser.Account, tag.ModuleID, sender.Name); //获取窗体的权限
                        //(form as IPurviewControllable).FormAuthorities = auth; //本窗体的权限值
                        //(form as IPurviewControllable).FormMenuName = sender.Name;//绑定打开窗体的菜单名
                    }
                }
                if (sender != null)
                {
                    Loginer.CurrentUser.FunctionId = sender.Name;
                    string path = Lamex.Common.PathHelper.GetIniFile();
                    Lamex.Common.IniFile ini = new Common.IniFile(path);

                    ini.IniWriteValue("FrequentlyFunction", sender.Name, DateTime.Now.ToString());
                    //else
                    //{
                    //    int m = int.Parse(ini.IniReadValue("FrequentlyFunction", sender.Name).ToString());
                    //    m += 1;
                    //    ini.IniWriteValue("FrequentlyFunction", sender.Name, m.ToString());
                    //}

                }
                form.Show();
                return form;
            }
            catch (Exception ex)
            {
                MessageBox.Show("打开窗体时出现错误！\r\n" + ex.Message);
                //Msg.Warning("打开窗体时出现错误！\r\n" + ex.Message);
                return null;
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }

       /// <summary>
       /// 打开带参数的窗体
       /// </summary>
       /// <param name="mdi"></param>
       /// <param name="form"></param>
       /// <param name="sender"></param>
       /// <returns></returns>
        public static Form OpenChildForm_Param(IMdiForm mdi, Form form, string sender)
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;
                //Form form = ActiveChildForm(mdi as Form, formType.ToString());
                // if (form != null) { form.Show(); return form; }
                // form = (Form)formType.Assembly.CreateInstance(formType.FullName);
                if (form == null) throw new Exception("未知窗体类型!");
                if (form is IMdiChildForm)
                {
                    form.MdiParent = (Form)mdi;
                    (form as IMdiChildForm).ToolbarRegister = mdi.MdiToolbar;
                    (form as IMdiChildForm).RegisterObserver(mdi.MdiObservers);
                }


                //if (form is IPurviewControllable)
                //{
                //    if (sender != null && sender.Tag is MenuItemTag)
                //    {
                //        MenuItemTag tag = sender.Tag as MenuItemTag;
                //        //int auth = new bllGroupAuthority().GetFormAuthority(Loginer.CurrentUser.Account, tag.ModuleID, sender.Name); //获取窗体的权限
                //        //(form as IPurviewControllable).FormAuthorities = auth; //本窗体的权限值
                //        //(form as IPurviewControllable).FormMenuName = sender.Name;//绑定打开窗体的菜单名
                //    }
                //}
                if (sender != null)
                {
                    Loginer.CurrentUser.FunctionId = sender;
                    string path =Lamex.Common.PathHelper. GetIniFile();
                    Lamex.Common.IniFile ini = new Common.IniFile(path);
                    int iCount = 1;
                    ini.IniWriteValue("FrequentlyFunction", sender, DateTime.Now.ToString());
                    //else
                    //{
                    //    int m = int.Parse(ini.IniReadValue("FrequentlyFunction", sender).ToString());
                    //    m += 1;
                    //    ini.IniWriteValue("FrequentlyFunction", sender, m.ToString());
                    //}

                }
                form.Show();
                return form;
            }
            catch (Exception ex)
            {
                //MessageBox.Show("打开窗体时出现错误！\r\n" + ex.Message);
                //Msg.Warning("打开窗体时出现错误！\r\n" + ex.Message);

                //提示用户在RibbonForm框架下无法通过跳转打开窗体
                //即使改为弹窗打开，窗体也不能正常关闭；同时因为没加载操作功能，且无法进行权限控制，存在风险
                MessageBox.Show("窗体无法加载！\r\n" + "如果是跳转窗体，请直接通过菜单打开！");
                return null;
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }
        public static Form OpenChildForm_Param(IMdiForm mdi, Form form, ToolStripMenuItem sender)
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;
                //Form form = ActiveChildForm(mdi as Form, formType.ToString());
                // if (form != null) { form.Show(); return form; }
                // form = (Form)formType.Assembly.CreateInstance(formType.FullName);
                if (form == null) throw new Exception("未知窗体类型!");
                if (form is IMdiChildForm)
                {
                    form.MdiParent = (Form)mdi;
                    (form as IMdiChildForm).ToolbarRegister = mdi.MdiToolbar;
                    (form as IMdiChildForm).RegisterObserver(mdi.MdiObservers);
                }

                if (form is IPurviewControllable)
                {
                    if (sender != null && sender.Tag is MenuItemTag)
                    {
                        MenuItemTag tag = sender.Tag as MenuItemTag;
                        //int auth = new bllGroupAuthority().GetFormAuthority(Loginer.CurrentUser.Account, tag.ModuleID, sender.Name); //获取窗体的权限
                        //(form as IPurviewControllable).FormAuthorities = auth; //本窗体的权限值
                        //(form as IPurviewControllable).FormMenuName = sender.Name;//绑定打开窗体的菜单名
                    }
                }
                if (sender != null)
                {
                    Loginer.CurrentUser.FunctionId = sender.Name;
                    string path = Lamex.Common.PathHelper.GetIniFile();
                    Lamex.Common.IniFile ini = new Common.IniFile(path);

                    ini.IniWriteValue("FrequentlyFunction", sender.Name, DateTime.Now.ToString());
                }
                form.Show();
                return form;
            }
            catch (Exception ex)
            {
                MessageBox.Show("打开窗体时出现错误！\r\n" + ex.Message);
                //Msg.Warning("打开窗体时出现错误！\r\n" + ex.Message);
                return null;
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }

        /// <summary>
        /// 打开子窗体.
        /// </summary>
        /// <param name="mdi">MDI主窗体</param>
        /// <param name="formType">子窗体的类型</param>
        /// <param name="ToolStripMenuItem">打开窗体的菜单项</param>
        public static Form OpenChildWebBrowse(IMdiForm mdi, Form frmWebForm , ToolStripMenuItem sender)
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;
                Form form = frmWebForm;
                //if (form != null) { form.Show(); return form; }
              

                //form = (Form)formType.Assembly.CreateInstance(formType.FullName);


                if (form == null) throw new Exception("未知窗体类型!");
         

                if (form is IMdiChildForm)
                {
                    form.MdiParent = (Form)mdi;
                    (form as IMdiChildForm).ToolbarRegister = mdi.MdiToolbar;
                    (form as IMdiChildForm).RegisterObserver(mdi.MdiObservers);
                }

                //支持权限控制的子窗体
                if (form is IPurviewControllable)
                {
                    if (sender != null && sender.Tag is MenuItemTag)
                    {
                        MenuItemTag tag = sender.Tag as MenuItemTag;
                        //int auth = new bllGroupAuthority().GetFormAuthority(Loginer.CurrentUser.Account, tag.ModuleID, sender.Name); //获取窗体的权限
                        //(form as IPurviewControllable).FormAuthorities = auth; //本窗体的权限值
                        //(form as IPurviewControllable).FormMenuName = sender.Name;//绑定打开窗体的菜单名
                    }
                }
                if (sender != null)
                {
                    Loginer.CurrentUser.FunctionId = sender.Name;
                    string path =Lamex.Common.PathHelper. GetIniFile();
                    Lamex.Common.IniFile ini = new Common.IniFile(path);
                    int iCount = 1;
                    ini.IniWriteValue("FrequentlyFunction", sender.Name, DateTime.Now.ToString());
                    //else
                    //{
                    //    int m = int.Parse(ini.IniReadValue("FrequentlyFunction", sender.Name).ToString());
                    //    m += 1;
                    //    ini.IniWriteValue("FrequentlyFunction", sender.Name, m.ToString());
                    //}

                }

                form.Show();
                return form;
            }
            catch (Exception ex)
            {
                MessageBox.Show("打开窗体时出现错误！\r\n" + ex.Message);
                //Msg.Warning("打开窗体时出现错误！\r\n" + ex.Message);
                return null;
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }

        /// <summary>
        /// 打开MDI子窗体
        /// </summary>
        /// <param name="mdi">MDI主窗体</param>
        /// <param name="formType">子窗体的类型</param>
        /// <returns></returns>
        public static Form OpenChildForm(IMdiForm mdi, Type formType)
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;
                Form child = ActiveChildForm(mdi as Form, formType.ToString());
                if (child != null) { child.Show(); return child; }

                Form form = (Form)formType.Assembly.CreateInstance(formType.FullName);
                if (form != null && form is Form)
                {
                    child = form as Form;

                    if (form is IMdiChildForm)
                    {
                        (child as IMdiChildForm).ToolbarRegister = mdi.MdiToolbar;
                        (child as IMdiChildForm).RegisterObserver(mdi.MdiObservers);
                        child.MdiParent = (Form)mdi;
                    }
                    child.Show();
                    return child;
                }
                else
                    throw new Exception("未知窗体类型!");
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="mdiParent">主窗体对象引用</param>
        /// <param name="formTypeName">子窗体的命名空间全名</param>
        /// <returns></returns>
        public static Form ActiveChildForm(Form mdiParent, string formTypeName)
        {
            for (int x = 0; x < mdiParent.MdiChildren.Length; x++)
            {
                string ss = mdiParent.MdiChildren[x].GetType().ToString().ToUpper();
                if (ss == formTypeName.ToUpper()) 
                {
                    IMdiChildForm child = mdiParent.MdiChildren[x] as IMdiChildForm;
                    if (child.AllowMultiInstatnce) continue; 
                    mdiParent.MdiChildren[x].Activate();
                    return mdiParent.MdiChildren[x];
                }
            }
            return null;
        }
        public static Form ActiveChildWebBrowse(Form mdiParent, string formTypeName)
        {
            for (int x = 0; x < mdiParent.MdiChildren.Length; x++)
            {
                string ss = mdiParent.MdiChildren[x].GetType().ToString().ToUpper();
                if (ss == formTypeName.ToUpper()) 
                {
                    IMdiChildForm child = mdiParent.MdiChildren[x] as IMdiChildForm;
                    if (child.AllowMultiInstatnce) continue; 
                    mdiParent.MdiChildren[x].Activate();
                    return mdiParent.MdiChildren[x];
                }
            }
            return null;
        }
    }
}
